package utils;

import io.minio.MinioClient;
import io.minio.PutObjectOptions;
import io.minio.errors.MinioException;
import org.apache.commons.io.FileUtils;


import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;


public class ImageUploadUtil {
    public static String IP="111.230.194.168";
    public static String PORT = "3004";
    public static String ACCESSKEY="minioadmin";
    public static String SECRETKEY="minioadmin";
    public static void uploadImage(String bucketName, String image,String newName)throws NoSuchAlgorithmException, IOException, InvalidKeyException{{
        uploadImage(bucketName,new File(image),newName);
    }}
    public static void uploadImage(String bucketName, File image,String newName)throws NoSuchAlgorithmException, IOException, InvalidKeyException{
        try {
            // 使用MinIO服务的URL，端口，Access key和Secret key创建一个MinioClient对象
            MinioClient minioClient = new MinioClient("http://"+IP+":"+PORT,ACCESSKEY,SECRETKEY);

            // 检查存储桶是否已经存在
            boolean isExist = minioClient.bucketExists(bucketName);
            if(isExist) {
                System.out.println("Bucket already exists.");
            } else {
                // 创建一个名为bucketName的存储桶
                minioClient.makeBucket(bucketName);
            }
            // 使用putObject上传一个文件到存储桶中。
            long size = FileUtils.sizeOf(image);
            FileInputStream fileInputStream=new FileInputStream(image);
            PutObjectOptions options=new PutObjectOptions(size,-1);
            minioClient.putObject(bucketName,newName, fileInputStream,options);

        } catch(MinioException e) {
            System.out.println("Error occurred: " + e);
        }
    }
    public static void main(String[] args) throws NoSuchAlgorithmException, IOException, InvalidKeyException{
        uploadImage("test", new File("C:\\Users\\Lenovo\\Pictures\\opt.jpg"),"mytest.jpg");
    }
}
